import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Layout, Menu, Icon, Dropdown, Avatar, Breadcrumb, Tooltip, LocaleProvider } from 'antd';
import zhCN from 'antd/lib/locale-provider/zh_CN';
import '../style/admin.less';
import { User } from '../stores/user';
import { asyncForm, asyncDelConfirm, asyncSMessage } from '../services/AsyncTools';

const { SubMenu } = Menu;
const { Header, Sider } = Layout;

const passwordItemList = [
  {
    key: 'password',
    name: '新密码',
    type: 'input',
    placeholder: '请输入新密码',
    require: true,
  },
];

export default class extends Component {
  constructor(props) {
    super(props);
    const { config, moduleMap } = props;
    const state = { routes: [] };
    if (config.module) {
      state.routes.push({
        name: config.module.name,
        path: moduleMap[config.module.key].path,
      });
    }
    if (config.group) {
      state.routes.push({
        name: config.group.name,
        path: moduleMap[config.module.key].groupMap[config.group.key].path,
      });
    }
    if (config.module && config.group) {
      if (moduleMap[config.module.key].groupMap[config.group.key].subList.length > 1 || config.showKey) {
        state.routes.push({
          name: config.title,
        });
      }
    }
    this.state = state;
  }

  render() {
    const { config } = this.props;
    return (
      <div className="admin" style={{ height: window.document.documentElement.clientHeight }}>
        {config.module ? this.renderLayoutView() : this.renderContentView(true)}
      </div>
    );
  }

  getUserconfigMenu() {
    return (
      <Menu
        style={{ width: '100px', textAlign: 'center' }}
        onClick={item => {
          switch (item.key) {
            case 'password':
              asyncForm('修改密码', passwordItemList, {}, data => {
                return User.editPassword(data).then(() => {
                  asyncSMessage('密码修改成功!');
                });
              });
              break;
            case 'logout':
              asyncDelConfirm('退出', '是否退出当前帐号?', () => {
                User.logout().then(() => {
                  asyncSMessage('帐号已退出!');
                });
              });
              break;
            default:
              break;
          }
        }}
      >
        <Menu.Item key="password">
          <Icon type="edit" />
          修改密码
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />
          退出登录
        </Menu.Item>
      </Menu>
    );
  }

  getOtherLink() {
    const { project } = this.props;
    return (
      <Menu
        style={{ width: '100px', textAlign: 'center' }}
        onClick={item => {
          toLink(item.key);
        }}
      >
        {project.otherLink.map(link => {
          return (
            <Menu.Item key={link.path}>
              <Icon type="link" />
              {link.title}
            </Menu.Item>
          );
        })}
      </Menu>
    );
  }

  renderLayoutView() {
    const { moduleList, moduleMap, config, user, project } = this.props;
    const { collapsed, logo, name, username, openMenu } = user;
    return (
      <LocaleProvider locale={zhCN}>
        <Layout>
          <Header id="layout-header" className={`${collapsed ? 'collapsed' : ''}`}>
            <Link to="/">
              <div id="logo">
                <img src={logo} />
                <h1>{name}</h1>
              </div>
            </Link>
            <Menu
              className="header-menu"
              theme="dark"
              mode="horizontal"
              defaultSelectedKeys={[config.module.key]}
              selectedKeys={[config.module.key]}
              onClick={e => {
                linkTo(e.item.props.path);
              }}
            >
              {moduleList.map(key => {
                const m = moduleMap[key];
                return (
                  <Menu.Item key={m.key} path={m.path}>
                    {m.name}
                  </Menu.Item>
                );
              })}
            </Menu>
            <div className="f-r">
              <Tooltip placement="bottom" title="使用文档">
                <Icon className="icon" type="question-circle" />
              </Tooltip>

              <Tooltip placement="bottom" title="消息">
                <Icon className="icon" type="bell" />
              </Tooltip>
              {project.otherLink && project.otherLink.length > 0 && (
                <Dropdown overlay={this.getOtherLink()} placement="bottomCenter">
                  <Icon className="icon" type="link" />
                </Dropdown>
              )}
              <Dropdown overlay={this.getUserconfigMenu()} placement="bottomCenter">
                <div className="user-info" style={{ display: 'inline-block' }}>
                  <Avatar className="avatar" size="small" icon="user" />
                  <span className="m-l-1">{username}</span>
                </div>
              </Dropdown>
            </div>
          </Header>
          <Layout>
            {config.group && (
              <Sider onCollapse={() => User.switchCollapse()} collapsible collapsed={collapsed} className="left-slider">
                <Menu
                  className="left-menu"
                  mode="inline"
                  key={`${collapsed}`}
                  defaultSelectedKeys={[config.showKey || config.key, config.group.key]}
                  defaultOpenKeys={collapsed ? [] : openMenu[config.module.key] || [config.group.key]}
                  style={{ height: '100%' }}
                  onClick={e => linkTo(e.item.props.path)}
                  onOpenChange={keys => !collapsed && User.openMenu(config.module.key, keys)}
                >
                  {moduleMap[config.module.key].groupList.map(key => {
                    const group = moduleMap[config.module.key].groupMap[key];
                    const hasSub = group.subList.length > 1;
                    const view = hasSub ? (
                      <SubMenu
                        key={group.key}
                        title={
                          <span>
                            <Icon type={group.icon} />
                            <span>{group.name}</span>
                          </span>
                        }
                      >
                        {group.subList.map(k => {
                          const sub = group.subMap[k];
                          return (
                            <Menu.Item key={sub.key} path={sub.path}>
                              <Icon type={sub.icon} />
                              <span>{sub.name || sub.title}</span>
                            </Menu.Item>
                          );
                        })}
                      </SubMenu>
                    ) : (
                      <Menu.Item key={group.key} path={group.path}>
                        <Icon type={group.icon} />
                        <span>{group.name}</span>
                      </Menu.Item>
                    );
                    return view;
                  })}
                </Menu>
              </Sider>
            )}
            <Layout className="page-layout">{this.renderContentView(false)}</Layout>
          </Layout>
        </Layout>
      </LocaleProvider>
    );
  }

  itemRender(route) {
    return !route.path ? <span>{route.name}</span> : <Link to={route.path}>{route.name}</Link>;
  }

  renderContentView(free) {
    const { config, children } = this.props;
    return (
      <div className="page-content">
        {!free && !config.free && (
          <Breadcrumb
            hidden={config.free || !config.module}
            itemRender={this.itemRender}
            routes={this.state.routes}
            separator="/"
          />
        )}
        {children}
      </div>
    );
  }
}
